export default ({ app }, inject) => {

      const toast = function (msg,time=2000) {
          return new Promise((resolve,reject)=>{
              let toast = document.querySelector('.ui-toast');
              if(!toast){
                  let div = document.createElement('div');
                  let p = document.createElement('p');
                  p.innerText = msg;
                  div.appendChild(p);
                  div.classList.add('ui-toast');
                  document.body.appendChild(div);
                  toast = div;
                  let body = document.body || document.documentElement;
                  let transitionEnd=(function(){
                      let transEndEventNames = {
                        WebkitTransition : 'webkitTransitionEnd',
                        MozTransition    : 'transitionend',
                        OTransition      : 'oTransitionEnd otransitionend',
                        transition       : 'transitionend'
                      }
                      for(let name in transEndEventNames){
                          if(typeof body.style[name] === "string"){
                              return transEndEventNames[name]
                          }
                      }
                  })();

                  toast.addEventListener(transitionEnd,e=>{
                      if(e.propertyName == 'top'){
                          if(toast.classList.contains('toast-out')){
                              toast.classList.remove('toast-out');
                              if(toast.isReplace){
                                  //toast.querySelector('p').innerText = msg;
                                  toast.classList.add('toast-in');
                              }
                          }
                      }
                  });
                  setTimeout(()=>{
                      toast.classList.add('toast-in');
                  },0);
              }else{
                  if(toast.timeout){
                      clearTimeout(toast.timeout);
                      toast.isReplace = true;
                      toast.classList.add('toast-out')
                      toast.classList.remove('toast-in');
                      toast.timeout = ""
                  }else{
                      //toast.querySelector('p').innerText = msg;
                      toast.classList.add('toast-in');
                  }
                  toast.querySelector('p').innerText = msg;
              }

              toast.timeout = setTimeout(()=>{
                  toast.timeout = "";
                  toast.isReplace = false;
                  toast.classList.add('toast-out')
                  toast.classList.remove('toast-in');
                  resolve();
              },time)
          })


      }

    inject('toast',toast);

}
